/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain an copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.beyondsw.palette.slice;

import com.beyondsw.palette.PaletteView;
import com.beyondsw.palette.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.rdb.ValuesBucket;
import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * MainAbilitySlice
 *
 * @since 2021-05-28
 */
public class MainAbilitySlice extends AbilitySlice implements PaletteView.Callback, Component.ClickedListener {
    private static final int QUALITY = 90; // 图片质量
    private Component mUndoView;
    private Component mRedoView;
    private Component mPenView;
    private Component mEraserView;
    private Component mClearView;
    private Image mClearImage;
    private Image mEraserImage;
    private Image mPenImage;
    private Image mRedoImage;
    private Image mUndoImage;
    private Component mSave;
    private PaletteView mPaletteView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        mPaletteView = (PaletteView) findComponentById(ResourceTable.Id_palette);
        mPaletteView.setCallback(this);

        mUndoView = findComponentById(ResourceTable.Id_undo);
        mRedoView = findComponentById(ResourceTable.Id_redo);
        mPenView = findComponentById(ResourceTable.Id_pen);
        mEraserView = findComponentById(ResourceTable.Id_eraser);
        mClearView = findComponentById(ResourceTable.Id_clear);
        mClearImage = (Image) findComponentById(ResourceTable.Id_imageClear);
        mEraserImage = (Image) findComponentById(ResourceTable.Id_imageEraser);
        mPenImage = (Image) findComponentById(ResourceTable.Id_imagePen);
        mRedoImage = (Image) findComponentById(ResourceTable.Id_imageRedo);
        mUndoImage = (Image) findComponentById(ResourceTable.Id_imageUndo);
        mSave = findComponentById(ResourceTable.Id_save);
        mUndoView.setClickedListener(this);
        mRedoView.setClickedListener(this);
        mPenView.setClickedListener(this);
        mEraserView.setClickedListener(this);
        mClearView.setClickedListener(this);
        mSave.setClickedListener(this);

        mUndoView.setEnabled(false);
        mUndoImage.setPixelMap(ResourceTable.Media_ic_undo_disable);
        mRedoView.setEnabled(false);
        mRedoImage.setPixelMap(ResourceTable.Media_ic_redo_disable);
        mPenView.setSelected(true);
        mPenImage.setPixelMap(ResourceTable.Media_ic_pen_selected);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onUndoRedoStatusChanged() {
        mUndoView.setEnabled(mPaletteView.canUndo());
        mRedoView.setEnabled(mPaletteView.canRedo());
        mUndoImage.setPixelMap(mPaletteView.canUndo()
                ? ResourceTable.Media_ic_undo_selected : ResourceTable.Media_ic_undo_disable);
        mRedoImage.setPixelMap(mPaletteView.canRedo()
                ? ResourceTable.Media_ic_redo_selected : ResourceTable.Media_ic_redo_disable);
    }

    @Override
    public void onClick(Component v) {
        switch (v.getId()) {
            case ResourceTable.Id_undo:
                mPaletteView.undo();
                break;
            case ResourceTable.Id_redo:
                mPaletteView.redo();
                break;
            case ResourceTable.Id_pen:
                v.setSelected(true);
                mEraserView.setSelected(false);
                mEraserImage.setPixelMap(ResourceTable.Media_ic_eraser_selected);
                mPaletteView.setDrawMode(PaletteView.Mode.DRAW);
                break;
            case ResourceTable.Id_eraser:
                v.setSelected(true);
                mPenView.setSelected(false);
                mPenImage.setPixelMap(ResourceTable.Media_ic_pen_selected);
                mPaletteView.setDrawMode(PaletteView.Mode.ERASER);
                break;
            case ResourceTable.Id_clear:
                mPaletteView.clear();
                break;
            case ResourceTable.Id_save:
                saveImage();
                break;
            default:
                break;
        }
    }

    private void saveImage() {
        PixelMap pixelMap = mPaletteView.buildPixelMap();
        Uri uri = saveImage(System.currentTimeMillis() + "testPalette", pixelMap);
        if (Uri.EMPTY_URI.equals(uri)) {
            new ToastDialog(getContext()).setText("保存失败").show();
        } else {
            new ToastDialog(getContext()).setText("画布保存到相册成功！").show();
        }
    }

    /**
     * pixelmap存储成流 ：
     *
     * @param fileName
     * @param pixelMap
     * @return Uri
     */
    private Uri saveImage(String fileName, PixelMap pixelMap) {
        try {
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(AVStorage.Images.Media.DISPLAY_NAME, fileName);
            valuesBucket.putString("relative_path", "DCIM/");
            valuesBucket.putString(AVStorage.Images.Media.MIME_TYPE, "image/JPEG");

            // 应用独占
            valuesBucket.putInteger("is_pending", 1);
            DataAbilityHelper helper = DataAbilityHelper.creator(this);
            int id = helper.insert(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));

            // 这里需要"w"写权限
            FileDescriptor fd = helper.openFile(uri, "w");
            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            OutputStream outputStream = new FileOutputStream(fd);
            packingOptions.format = "image/jpeg";
            packingOptions.quality = QUALITY;
            boolean isSuccess = imagePacker.initializePacking(outputStream, packingOptions);
            if (isSuccess) {
                isSuccess = imagePacker.addImage(pixelMap);
                if (isSuccess) {
                    long dataSize = imagePacker.finalizePacking();
                }
            }
            outputStream.flush();
            outputStream.close();
            valuesBucket.clear();

            // 解除独占
            valuesBucket.putInteger("is_pending", 0);
            helper.update(uri, valuesBucket, null);
            return uri;
        } catch (IOException | DataAbilityRemoteException e) {
            return Uri.EMPTY_URI;
        }
    }
}
